<template>
   <div class="address-container nav-bar-top">
     <van-nav-bar class="nav-bar" title="我的地址" left-arrow @click-left="$router.back()"/>
     <van-address-list
       class="p0"
       v-model="chosenAddressId"
       :list="addressList"
       default-tag-text="默认"
       :switchable="switchable"
       @select="selectAddress"
       @edit="editAddress"
       @add="addAddress"
     />
   </div>
</template>

<script>
import { mapState } from 'vuex'
import userApi from '@/api/userApi'
import constants from '@/config/constants'

export default {
  name: 'addressList',
  computed: {
    ...mapState(['user', 'cartList'])
  },
  created () {
    // 获取收货地址列表
    this.getAddressList();
    // 设置选中
    this.chosenAddressId = this.$route.query.id;
    if(this.$route.query.edit){
      this.switchable = true;
    }
  },
  data () {
    return {
      switchable: false,
      chosenAddressId: '',
      addressList: [],
      sourceAddressList: []
    }
  },
  methods: {
    /* 获取收货地址列表 */
    async getAddressList () {
      if(this.user){
        const result = await userApi.addressList(this.user.id);
        if(result.code == constants.SUCCESS){
          var addressList = [];
          result.data.forEach(address => {
            addressList.push({
              id: address.id.toString(),
              name: address.receiverName,
              tel: address.phone,
              address: address.provinceName+address.cityName+address.areaName+address.address,
              isDefault: address.defaultFlag == '0' ? false : true
            })
          });
          this.addressList = addressList;
          this.sourceAddressList = result.data;
        }
      }
    },
    /* 选中地址 */
    selectAddress (item, index) {
      if(this.$route.query.edit){
        this.$store.commit(constants.STORE.UPDATE_SELECT_ADDRESS_INFO, this.sourceAddressList[index]);
        this.$router.go(-1);
      }
    },
    /* 添加地址 */
    addAddress (item, index) {
      this.$router.push({path: '/addressEdit', query: {id: ''}});
    },
    /* 编辑地址 */
    editAddress (item, index) {
      this.$router.push({path: '/addressEdit', query: {id: item.id}});
    }
  }
}
</script>

<style lang="scss">
.address-container{
  padding-top: 5px;
  .van-address-list{
    /deep/ .van-address-item{
      margin-bottom: 0;
      padding: 15px 10px 15px 20px;
      margin: 0 10px 7px 10px;
      border-radius: 5px;
      /deep/ .van-radio{
        margin-bottom: 0px;
      }
      /deep/ .van-address-item__tag{
        padding: 0 5px;
        border-radius: 5px;
      }
      /deep/ .van-address-item__name{
        font-size: 14px;
      }
    }
    .van-address-list__bottom{
      background: none;
      bottom: 20px;
      .van-address-list__add{
        height: 44px;
      }
    }
  }
}
</style>
